package com.csist.task;

import com.csist.message.FileMessage;
import com.csist.server.Server;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

/**
 * @ClassName ServerRunnable
 * @Description TODO
 * @Author User
 * @Date 2021/6/10 10:45
 * @ModifyDate 2021/6/10 10:45
 * @Version 1.0
 */
public class ServerRunnable implements Runnable{
    private Socket socket;
    private FileOutputStream fos;
    /**服务器里客户端上传文件的存储路径*/
    private String path = "D:\\save";
    @Override
    public void run() {
            receiveFile();
    }

    /**
     * 接收来自客户端上传的文件
     */
    public void receiveFile(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(socket.getInputStream());
            Object object = ois.readObject();
            ArrayList<FileMessage> fileMessages = new ArrayList<>();
            if (object instanceof ArrayList<?>){
                fileMessages = (ArrayList<FileMessage>)object;
            }
            for (FileMessage f:fileMessages) {
                System.out.println("接收到来自"+socket.getInetAddress().getHostAddress()+"的文件"+f.getName());
                saveFile(f,path);
            }
            System.out.println("文件以存储到："+path);
            socket.getOutputStream().write("文件发送成功".getBytes(StandardCharsets.UTF_8));
        } catch (IOException | ClassNotFoundException e) {
            close();
            e.printStackTrace();
        } finally {
            close();
        }
    }

    /**
     * 将接收的文件存储到"D:\\save"
     * @param fileMessage 接收的文件对象
     * @param path 存储路径
     */
    public void saveFile(FileMessage fileMessage,String path){
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }

        //获取当前时间作为文件名
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String nowTime = sdf.format(dateTime);
        try {
            fos = new FileOutputStream(file+"\\"+nowTime+fileMessage.getType());
            fos.write(fileMessage.getContent());
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭socket
     */
    public void close(){
        if (fos!=null){
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (socket!=null){
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public ServerRunnable(Socket socket) {
        this.socket = socket;
    }
}
